package com.syj.jsxjj.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.syj.jsxjj.app.App;
import com.syj.jsxjj.app.AppManager;
import com.syj.jsxjj.config.Constant;
import com.syj.jsxjj.dialog.ActivityFragmentDialog;
import com.syj.jsxjj.events.ChangeTabMainEvent;
import com.syj.jsxjj.events.FragmentRefreshEvent;
import com.syj.jsxjj.events.RefreshUIEvent;
import com.syj.jsxjj.events.UIBaseEvent;
import com.syj.jsxjj.ui.lend.presenter.ActivityPresenter;
import com.syj.jsxjj.ui.login.activity.LoginActivity;
import com.syj.jsxjj.ui.login.activity.RegisterPhoneActivity;
import com.syj.jsxjj.util.LogUtils;
import com.syj.jsxjj.util.SpUtil;
import com.syj.jsxjj.util.StringUtil;
import com.syj.jsxjj.util.ToastUtil;
import com.syj.jsxjj.xgpush.XGPushHelper;
import com.syj.jsxjj.R;
import com.syj.jsxjj.base.BaseActivity;
import com.syj.jsxjj.ui.lend.bean.ActivityBean;
import com.syj.jsxjj.ui.lend.contract.ActivityContract;
import com.syj.jsxjj.widget.MyRadioButton;
import com.tendcloud.tenddata.TCAgent;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * 首页
 * xiejingwen
 */
public class MainActivity extends BaseActivity<ActivityPresenter> implements ActivityContract.View {
    @BindView(R.id.container)
    FrameLayout mContainer;
    @BindView(R.id.group)
    RadioGroup mGroup;
    @BindView(R.id.rb_lend)
    MyRadioButton mRbLend;
    @BindView(R.id.rb_discover)
    MyRadioButton mRbDiscover;
    @BindView(R.id.rb_rent_lend)
    MyRadioButton mRbRentLend;
    @BindView(R.id.rb_account)
    MyRadioButton mRbAccount;
    private FragmentFactory.FragmentStatus toTabIndex = FragmentFactory.FragmentStatus.None;
    private int oldCheckId = R.id.rb_lend;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }
    @Override
    public void initPresenter() {
        mPresenter.init(this);
    }

    @Override
    public void loadData() {
        EventBus.getDefault().register(this);
        mGroup.setOnCheckedChangeListener(changeListener);
        check(FragmentFactory.FragmentStatus.Lend);
        registerPush();
        mPresenter.loadActivity();
    }

    public void check(FragmentFactory.FragmentStatus status) {
        mGroup.check(getCheckIdByStatus(status));
    }

    /************
     * 注册信鸽推送
     */
    private void registerPush() {
        //        XGPushHelper.getInstance().unRegisterPush(App.getContext());
        Log.e("CACHE_TAG_UID====", SpUtil.getString(Constant.CACHE_TAG_UID));
        String account = App.getConfig().getLoginStatus() ? SpUtil.getString(Constant.CACHE_TAG_UID) : "";
        XGPushHelper.getInstance().registerPush(App.getContext(), account);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mGroup.setOnCheckedChangeListener(changeListener);

    }

    OnCheckedChangeListener changeListener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.rb_lend:
                    toTabIndex = FragmentFactory.FragmentStatus.Lend;
                    changeTab(FragmentFactory.FragmentStatus.Lend);
                    oldCheckId = R.id.rb_lend;
                    break;
                case R.id.rb_account:
                    toTabIndex = FragmentFactory.FragmentStatus.Account;
                    if (App.getConfig().getLoginStatus()) {

                        changeTab(FragmentFactory.FragmentStatus.Account);
                    } else {
                        toLogin();
                        return;
                    }
                    break;
                case R.id.rb_rent_lend:
                    toTabIndex = FragmentFactory.FragmentStatus.RentLend;
                    if (App.getConfig().getLoginStatus()) {
                        changeTab(FragmentFactory.FragmentStatus.RentLend);
                    } else {
                        toLogin();
                        return;
                    }
                    break;
                case R.id.rb_discover:
                    toTabIndex = FragmentFactory.FragmentStatus.Discover;
                    if (App.getConfig().getLoginStatus()) {
                        changeTab(FragmentFactory.FragmentStatus.Discover);
                    } else {
                        toLogin();
                        return;
                    }
                    break;
                default:
                    break;

            }
        }
    };

    private void toLogin() {
        mGroup.setOnCheckedChangeListener(null);
        ((RadioButton) findViewById(oldCheckId)).setChecked(true);
        String uName = SpUtil.getString(Constant.CACHE_TAG_USERNAME);
        LogUtils.loge(uName);
        if (!StringUtil.isBlank(uName) && StringUtil.isMobileNO(uName)) {
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            intent.putExtra("tag", StringUtil.changeMobile(uName));
            intent.putExtra("phone", uName);
            startActivity(intent);
        } else {
            Intent intent = new Intent(MainActivity.this, RegisterPhoneActivity.class);
            startActivity(intent);
        }
    }

    /***********
     * eventBus 监听
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(UIBaseEvent event) {
        if (event instanceof RefreshUIEvent) {
            int code = ((RefreshUIEvent) event).getType();
            if (code == UIBaseEvent.EVENT_LOGIN)//登录
            {
                registerPush();
                if (toTabIndex != odlState)//切换
                {
                    changeTab(toTabIndex);
                    ((RadioButton) findViewById(getCheckIdByStatus(toTabIndex))).setChecked(true);
                }
                EventBus.getDefault().post(new FragmentRefreshEvent(code));
            } else if (code == UIBaseEvent.EVENT_LOGOUT) {
                registerPush();
                //默认到首页
                changeTab(FragmentFactory.FragmentStatus.Lend);
                ((RadioButton) findViewById(getCheckIdByStatus(FragmentFactory.FragmentStatus.Lend))).setChecked(true);
                EventBus.getDefault().post(new FragmentRefreshEvent(code));
            } else if (code == UIBaseEvent.EVENT_LOAN_SUCCESS) {
                EventBus.getDefault().post(new FragmentRefreshEvent(code));
            }
        } else if (event instanceof ChangeTabMainEvent) {
            changeTab(((ChangeTabMainEvent) event).getTab());
        }
    }


    /***********
     * 获取所选状态的checkId
     *
     * @return
     */
    public int getCheckIdByStatus(FragmentFactory.FragmentStatus status) {
        int id = R.id.rb_lend;
        switch (status) {
            case Account:

                id = R.id.rb_account;
                break;
            case Lend:

                id = R.id.rb_lend;
                break;
            case RentLend:

                id = R.id.rb_rent_lend;
                break;
            case Discover:

                id = R.id.rb_discover;
                break;
            default:
                break;
        }

        return id;
    }

    /***********
     * 切换导航栏
     */
    private FragmentFactory.FragmentStatus odlState = FragmentFactory.FragmentStatus.None;

    public void changeTab(FragmentFactory.FragmentStatus status) {
        if (status == odlState) {
            return;
        } else if (status == FragmentFactory.FragmentStatus.Lend) {
            mRbLend.setChecked(true);
            mRbRentLend.setChecked(false);
            mRbAccount.setChecked(false);
            mRbDiscover.setChecked(false);
        } else if (status == FragmentFactory.FragmentStatus.Account) {
            mRbLend.setChecked(false);
            mRbRentLend.setChecked(false);
            mRbAccount.setChecked(true);
            mRbDiscover.setChecked(false);
        } else if (status == FragmentFactory.FragmentStatus.Discover) {
            mRbLend.setChecked(false);
            mRbRentLend.setChecked(false);
            mRbAccount.setChecked(false);
            mRbDiscover.setChecked(true);
        } else if (status == FragmentFactory.FragmentStatus.RentLend) {
            mRbLend.setChecked(false);
            mRbRentLend.setChecked(true);
            mRbAccount.setChecked(false);
            mRbDiscover.setChecked(false);
        }
        FragmentFactory.changeFragment(getSupportFragmentManager(), status, R.id.container);
        odlState = status;
    }


    private long exitTime = 0;

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            ToastUtil.showToast("再按一次退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            super.onBackPressed();
        }
    }

    public RadioGroup getGroup() {
        return mGroup;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //MobclickAgent.onKillProcess(this);
        EventBus.getDefault().unregister(this);
        AppManager.getInstance().AppExit(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);

        if (resultCode == 1024) {//优惠卷活动跳出
            check(FragmentFactory.FragmentStatus.None);
            changeTab(FragmentFactory.FragmentStatus.Lend);

        }
    }

    @Override
    public void showLoading(String content) {

    }

    @Override
    public void stopLoading() {

    }

    @Override
    public void showErrorMsg(String msg, String type) {

    }

    @Override
    public void loadActivitySuccess(ActivityBean result) {
        if ("0".equals(result.getTcStatus())) {//0为显示，其他为不显示
            //缓存图片url与点击url。每个活动只弹出一次
            String imgUrl = SpUtil.getString(Constant.CACHE_TAG_ACTIVITY_IMGURL);
            String url = SpUtil.getString(Constant.CACHE_TAG_ACTIVITY_URL);
            if (!result.getTcImage().equals(imgUrl) || !result.getTcUrl().contains(url)) {
                SpUtil.putString(Constant.CACHE_TAG_ACTIVITY_IMGURL, result.getTcImage());
                SpUtil.putString(Constant.CACHE_TAG_ACTIVITY_URL, result.getTcUrl());
                ActivityFragmentDialog.newInstance(result.getTcImage(), result.getTcUrl())
                        .show(getSupportFragmentManager(), ActivityFragmentDialog.TAG);
            }

            //弹窗埋点
            if (result.getTcImage().contains("xyhedw0@2x.png")) {//无额度新用户
                MobclickAgent.onEvent(this, "Home_NoLimit_NewUser");
                TCAgent.onEvent(this, "Home_NoLimit_NewUser");

            } else if (result.getTcImage().contains("lyhedw0@2x.png")) {//无额度老用户
                MobclickAgent.onEvent(this, "Home_NoLimit_OldUser");
                TCAgent.onEvent(this, "Home_NoLimit_OldUser");

            } else if (result.getTcImage().contains("sqsbyd@2x.png")) {//首页被拒
                MobclickAgent.onEvent(this, "Home_Audit_Refuse");
                TCAgent.onEvent(this, "Home_Audit_Refuse");
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
